package com.lw.leetcode.str.b;

import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * 1717. 删除子字符串的最大得分
 *
 * @author liw
 * @version 1.0
 * @date 2022/1/9 15:19
 */
public class MaximumGain {


    public static void main(String[] args) {
        MaximumGain test = new MaximumGain();
        // 20
//        String str = "aabbaaxybbaabb";
//        int x = 5;
//        int y = 4;

        // 19
//        String str = "cdbcbbaaabab";
//        int x = 4;
//        int y = 5;

        // 9
//        String str = "abab";
//        int x = 4;
//        int y = 5;

        // 9
//        String str = "ababababa";
//        int x = 14;
//        int y = 5;

        // 112374
        String str = "aabbabkbbbfvybssbtaobaaaabataaadabbbmakgabbaoapbbbbobaabvqhbbzbbkapabaavbbeghacabamdpaaqbqabbjbababmbakbaabajabasaabbwabrbbaabbafubayaazbbbaababbaaha";
        int x = 1926;
        int y = 4320;

        int i = test.maximumGain(str, x, y);
        System.out.println(i);
    }


    private int length;
    public int maximumGain(String s, int x, int y) {
        int sum = 0;
        char a = 'a';
        char b = 'b';
        if (y > x) {
            b = 'a';
            a = 'b';
            int item = x;
            x = y;
            y = item;
        }
        length = s.length();
        char[] arr = s.toCharArray();
        Stack<Character> stack = new Stack<>();
        sum += find(arr, a, b, x, stack);
        stack.clear();
        sum += find(arr, b, a, y, stack);
        return sum;
    }

    public int find(char[] arr, char a, char b, int t, Stack<Character> stack) {
        int sum = 0;
        int length = this.length;
        for (int i = 0; i < length; i++) {
            if (arr[i] == b) {
                if (!stack.isEmpty() && stack.peek() == a) {
                    stack.pop();
                    sum += t;
                } else {
                    stack.add(b);
                }
            } else {
                stack.add(arr[i]);
            }
        }
        length = stack.size();
        for (int i = length - 1; i >= 0; i--) {
            arr[i] = stack.pop();
        }
        this.length = length;
        return sum;
    }

}
